package com.zeros.latte.net.download;

import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;

import com.zeros.latte.apps.Latte;
import com.zeros.latte.net.callback.IRequest;
import com.zeros.latte.net.callback.ISuccess;
import com.zeros.latte.util.FileUtil;

import java.io.File;
import java.io.InputStream;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;

/**
 * 异步任务下载 on 2018/2/1.
 * 完成
 */

public class SaveFileTask extends AsyncTask<Object, Void, File> {
    //    传入的是Object--可能是string或其他，不需要进度void，返回是file

    private final IRequest REQUEST;
    private final ISuccess SUCCESS;

    SaveFileTask(IRequest REQUEST, ISuccess SUCCESS) {
        this.REQUEST = REQUEST;
        this.SUCCESS = SUCCESS;
    }

    /**
     * 异步操作
     *
     * @param params 传入的参数
     * @return 返回file
     */
    @Override
    protected File doInBackground(Object... params) {
//        传参
        String downloadDir = (String) params[0];
        String extension = (String) params[1];
        final ResponseBody body = (ResponseBody) params[2]; //第三个参数传入body
        final String name = (String) params[3];
        final InputStream is = body.byteStream(); //得到输入流

        if (downloadDir == null || downloadDir.equals("")) {
            downloadDir = "down_loads";             //指定下载目录
        }
        if (extension == null || extension.equals("")) {
            extension = ""; //
        }

//        利用封装的一系列file方法
        if (name == null) {
            return FileUtil.writeToDisk(is, downloadDir, extension.toUpperCase(), extension);
        } else {
//            如果有完整名字name-直接创建
            return FileUtil.writeToDisk(is, downloadDir, name);
        }
    }

    /**
     * 异步完成回到主线程的操作
     *
     * @param file
     */
    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        if (SUCCESS != null) {
            SUCCESS.onSuccess(file.getPath());
        }
        if (REQUEST != null) {
            REQUEST.onRequestEnd();
        }
        autoInstallApk(file);
    }

    //    安转Apk
    private void autoInstallApk(File file) {
        if (FileUtil.getExtension(file.getPath()).equals("apk")) {
            final Intent install = new Intent();
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//新启任务栈-有可能在后台
            install.setAction(Intent.ACTION_VIEW);
            install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            Latte.getApplicationContext().startActivity(install);
        }
    }


}
